/**
 * 事件系统
 * @type {{}}
 */
import store from "@/kim/store";

var dict = {}

function on(name, _cb) {
    var cbs = dict[name]
    if (!cbs) {
        cbs = dict[name] = [];
    }
    if (cbs.indexOf(_cb) == -1) {

    }
    cbs.push(_cb);
}

function fire(name, argsArr) {
    var cbs = dict[name]
    if (cbs) {
        for (var i in cbs) {
            cbs[i].apply(window, argsArr);
            if (cbs[i].once){
                cbs.splice(i, 1);
            }
        }
    }
}

function off(name, _cb) {
    var cbs = dict[name]
    if (cbs) {
        if (!_cb) {
            delete dict[name];
        }else{
            for (let i = 0; i < cbs.length; ) {
                if (cbs[i] == _cb) {
                    cbs.splice(i, 1);
                }else{
                    i++;
                }
            }
        }
    }
}

function once(name, _cb) {
    _cb.once = true;
    on(name, _cb);
}

/**
 * 全局事件名
 * @type {{img_load: string, img_click: string, file_copy: string, img_dblclick: string}}
 */
const e = {
    img_click:'itsub_kim_ev_chat_img_click',
    img_dblclick:'itsub_kim_ev_chat_img_dblclick',
    img_load:'itsub_kim_ev_chat_img_load',
    file_copy:'itsub_kim_ev_chat_file_copy',
}

/**
 * 当聊天消息的图片被点击
 * @param el
 */
window[e.img_click] = function (el) {
    console.log('图片点击')
    fire('msg-img-click',[el]);
};
window[e.img_dblclick] = function (el) {
    console.log('图片双击')
    fire('msg-img-dblclick',[el]);
};
window[e.img_load] = function (el) {
    console.log('聊天图片加载完成')
    //原生js取5层父元素
    let mbox = el;
    for (let i = 0; i < 5; i++) {
        mbox = mbox.parentNode;
    }
    //把上面的代码换成原生js
    mbox.scrollTop = mbox.scrollHeight;
    fire('msg-img-load',[el]);
}
window[e.file_copy] = function (url,el) {
    console.log('复制链接')
    fire('msg-file-copy',[el]);
}


export default {
    on,fire,off,once,e
}
